package cn.tedu.egweibo2.base.exception;

import cn.tedu.egweibo2.base.response.JsonResult;
import cn.tedu.egweibo2.base.response.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("handleMethodArgumentNotValidException:"+data);

        return new JsonResult(Status.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("handleConstraintViolationException:"+data);

        return new JsonResult(Status.VALIDATED_ERROR,data);
    }
}
